package com.jplus.service.impl;

import com.jplus.dao.RegisterVarDao;
import com.jplus.dao.UserDao;
import com.jplus.entity.User;
import com.jplus.enums.ResultEnum;
import com.jplus.exception.SFUmbrellaException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;


@Slf4j
@Service
public class RegisterTimer extends Thread{

    private UserDao userDao;

    private RegisterVarDao registerVarDao;

    private User user;

    public RegisterTimer(UserDao userDao, RegisterVarDao registerVarDao, User user) {
        this.userDao = userDao;
        this.registerVarDao = registerVarDao;
        this.user = user;
    }

    public RegisterTimer() {}

    @Override
    public void run() {
        Timer timer = new Timer();
        System.out.println("-------开始执行注册计时任务--------");
        log.info("开始执行注册计时任务");
        timer.schedule(new TimerTask() {
            public void run() {
                try {
                    // 清除register_var表里面关于验证码发送次数的信息
                    registerVarDao.deleteRegisterCount(user.getPhone());
                    if (userDao.getAuthCodeByPhone(user.getPhone()) != null) {
                        // 清除user表里面的信息
                        userDao.deleteOneUserByPhone(user.getPhone());
                        System.out.println("=====已经清除用户表里面刚注册的信息=====");
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    log.warn("计时器清空用户记录异常,信息{}", e.getMessage());
                    throw new SFUmbrellaException(ResultEnum.TIMER_ERROR);
                }
            }
        }, 300000);// 延迟5 mins【300000】后执行

        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("-------关闭注册计时任务--------");
                log.info("关闭注册计时任务");
                timer.cancel();
            }
        }, 301000); // 当上一个timer执行完毕后关闭timer301000
    }

}
